#!/usr/bin/env python3
"""
生成macOS ICNS格式图标文件
使用系统的iconutil工具
"""

import os
import subprocess
import shutil

def create_icns():
    """生成macOS ICNS格式图标"""
    icons_dir = "/Users/ethan/Codes/longimagereader/icons"

    # 创建iconset临时目录
    iconset_dir = os.path.join(icons_dir, "app.iconset")
    if os.path.exists(iconset_dir):
        shutil.rmtree(iconset_dir)
    os.makedirs(iconset_dir)

    print("创建macOS iconset...")

    # macOS iconset需要的文件映射
    # 格式：(源文件, iconset中的文件名)
    iconset_files = [
        ("app_16x16.png", "icon_16x16.png"),
        ("app_32x32.png", "icon_16x16@2x.png"),
        ("app_32x32.png", "icon_32x32.png"),
        ("app_64x64.png", "icon_32x32@2x.png"),
        ("app_128x128.png", "icon_128x128.png"),
        ("app_256x256.png", "icon_128x128@2x.png"),
        ("app_256x256.png", "icon_256x256.png"),
        ("app_512x512.png", "icon_256x256@2x.png"),
        ("app_512x512.png", "icon_512x512.png"),
        ("app_512x512.png", "icon_512x512@2x.png")  # 1024x1024由512x512生成
    ]

    # 复制PNG文件到iconset目录
    for src_file, dst_file in iconset_files:
        src_path = os.path.join(icons_dir, src_file)
        dst_path = os.path.join(iconset_dir, dst_file)

        if os.path.exists(src_path):
            if dst_file == "icon_512x512@2x.png":
                # 为@2x版本生成1024x1024图片
                from PIL import Image
                img = Image.open(src_path)
                img_1024 = img.resize((1024, 1024), Image.Resampling.LANCZOS)
                img_1024.save(dst_path, "PNG")
                print(f"✓ 生成 {dst_file} (1024x1024)")
            else:
                shutil.copy2(src_path, dst_path)
                print(f"✓ 复制 {dst_file}")
        else:
            print(f"⚠️  警告：找不到源文件 {src_file}")

    # 使用iconutil生成ICNS文件
    icns_path = os.path.join(icons_dir, "app.icns")
    try:
        cmd = ["iconutil", "-c", "icns", iconset_dir, "-o", icns_path]
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        print(f"✅ ICNS图标已生成: {icns_path}")
    except subprocess.CalledProcessError as e:
        print(f"❌ 错误：生成ICNS失败")
        print(f"   命令: {' '.join(cmd)}")
        print(f"   错误: {e.stderr}")
        return False
    except FileNotFoundError:
        print("❌ 错误：找不到iconutil工具（需要macOS系统）")
        return False

    # 清理临时目录
    shutil.rmtree(iconset_dir)
    print("✓ 清理临时文件")

    return True

if __name__ == "__main__":
    create_icns()